package com.pm.controller;

import com.pm.entity.DailyReport;
import com.pm.entity.User;
import com.pm.service.DailyReportService;
import com.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 日报管理控制器
 */
@RestController
@RequestMapping("/api/daily-reports")
@CrossOrigin(origins = "*")
public class DailyReportController {
    
    @Autowired
    private DailyReportService dailyReportService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 获取所有日报
     */
    @GetMapping
    public ResponseEntity<List<DailyReport>> getAllDailyReports() {
        List<DailyReport> reports = dailyReportService.getAllDailyReports();
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 根据ID获取日报
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getDailyReportById(@PathVariable String id) {
        try {
            DailyReport report = dailyReportService.findById(id);
            if (report == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "日报不存在");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(report);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取日报信息失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 创建日报
     */
    @PostMapping
    public ResponseEntity<?> createDailyReport(@RequestBody DailyReport report, Authentication authentication) {
        try {
            // 设置日报提交者为当前用户
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            report.setUserId(currentUser.getId());
            
            DailyReport createdReport = dailyReportService.createDailyReport(report);
            
            Map<String, Object> response = new HashMap<>();
            response.put("report", createdReport);
            response.put("message", "日报创建成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新日报
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateDailyReport(@PathVariable String id, @RequestBody DailyReport report, Authentication authentication) {
        try {
            // 检查权限：只有日报提交者可以更新日报
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            DailyReport existingReport = dailyReportService.findById(id);
            
            if (existingReport == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "日报不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingReport.getUserId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限修改此日报");
                return ResponseEntity.badRequest().body(error);
            }
            
            report.setId(id);
            report.setUserId(existingReport.getUserId()); // 保持原提交者
            DailyReport updatedReport = dailyReportService.updateDailyReport(report);
            
            Map<String, Object> response = new HashMap<>();
            response.put("report", updatedReport);
            response.put("message", "日报更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 删除日报
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteDailyReport(@PathVariable String id, Authentication authentication) {
        try {
            // 检查权限：只有日报提交者可以删除日报
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            DailyReport existingReport = dailyReportService.findById(id);
            
            if (existingReport == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "日报不存在");
                return ResponseEntity.badRequest().body(error);
            }
            
            if (!existingReport.getUserId().equals(currentUser.getId())) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "无权限删除此日报");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean deleted = dailyReportService.deleteDailyReport(id);
            if (!deleted) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "删除日报失败");
                return ResponseEntity.badRequest().body(error);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "日报删除成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "删除日报失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 获取我的日报
     */
    @GetMapping("/my-reports")
    public ResponseEntity<List<DailyReport>> getMyDailyReports(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        List<DailyReport> reports = dailyReportService.findByUserId(currentUser.getId());
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 根据项目ID获取日报
     */
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<DailyReport>> getDailyReportsByProjectId(@PathVariable String projectId) {
        List<DailyReport> reports = dailyReportService.findByProjectId(projectId);
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 根据用户ID获取日报
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<DailyReport>> getDailyReportsByUserId(@PathVariable String userId) {
        List<DailyReport> reports = dailyReportService.findByUserId(userId);
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 获取指定用户指定日期的日报
     */
    @GetMapping("/user/{userId}/date/{date}")
    public ResponseEntity<?> getDailyReportByUserIdAndDate(
            @PathVariable String userId, 
            @PathVariable String date) {
        try {
            DailyReport report = dailyReportService.findByUserIdAndDate(userId, date);
            if (report == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "未找到指定日期的日报");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(report);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取日报失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 获取我今天的日报
     */
    @GetMapping("/my-today")
    public ResponseEntity<?> getMyTodayReport(Authentication authentication) {
        try {
            String currentUsername = authentication.getName();
            User currentUser = userService.findByUsername(currentUsername);
            String today = LocalDate.now().toString();
            
            DailyReport report = dailyReportService.findByUserIdAndDate(currentUser.getId(), today);
            if (report == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "今日尚未提交日报");
                return ResponseEntity.badRequest().body(error);
            }
            return ResponseEntity.ok(report);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取今日日报失败");
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 根据日期范围获取日报
     */
    @GetMapping("/date-range")
    public ResponseEntity<List<DailyReport>> getDailyReportsByDateRange(
            @RequestParam String startDate,
            @RequestParam String endDate) {
        List<DailyReport> reports = dailyReportService.findByDateRange(startDate, endDate);
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 根据用户ID和日期范围获取日报
     */
    @GetMapping("/user/{userId}/date-range")
    public ResponseEntity<List<DailyReport>> getDailyReportsByUserIdAndDateRange(
            @PathVariable String userId,
            @RequestParam String startDate,
            @RequestParam String endDate) {
        List<DailyReport> reports = dailyReportService.findByUserIdAndDateRange(userId, startDate, endDate);
        return ResponseEntity.ok(reports);
    }
    
    /**
     * 检查今日是否已提交日报
     */
    @GetMapping("/check-today")
    public ResponseEntity<Map<String, Boolean>> checkTodayReportSubmitted(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        boolean submitted = dailyReportService.hasSubmittedTodayReport(currentUser.getId());
        
        Map<String, Boolean> response = new HashMap<>();
        response.put("submitted", submitted);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户本周工作时长统计
     */
    @GetMapping("/weekly-hours/{userId}")
    public ResponseEntity<Map<String, Double>> getWeeklyWorkingHours(@PathVariable String userId) {
        double hours = dailyReportService.getWeeklyWorkHours(userId);
        
        Map<String, Double> response = new HashMap<>();
        response.put("weeklyHours", hours);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取用户本月工作时长统计
     */
    @GetMapping("/monthly-hours/{userId}")
    public ResponseEntity<Map<String, Double>> getMonthlyWorkingHours(@PathVariable String userId) {
        int currentMonth = LocalDate.now().getMonthValue();
        double hours = dailyReportService.getMonthlyWorkHours(userId, currentMonth);
        
        Map<String, Double> response = new HashMap<>();
        response.put("monthlyHours", hours);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取我的本周工作时长统计
     */
    @GetMapping("/my-weekly-hours")
    public ResponseEntity<Map<String, Double>> getMyWeeklyWorkingHours(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        double hours = dailyReportService.getWeeklyWorkHours(currentUser.getId());
        
        Map<String, Double> response = new HashMap<>();
        response.put("weeklyHours", hours);
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 获取我的本月工作时长统计
     */
    @GetMapping("/my-monthly-hours")
    public ResponseEntity<Map<String, Double>> getMyMonthlyWorkingHours(Authentication authentication) {
        String currentUsername = authentication.getName();
        User currentUser = userService.findByUsername(currentUsername);
        int currentMonth = LocalDate.now().getMonthValue();
        double hours = dailyReportService.getMonthlyWorkHours(currentUser.getId(), currentMonth);
        
        Map<String, Double> response = new HashMap<>();
        response.put("monthlyHours", hours);
        
        return ResponseEntity.ok(response);
    }
}